<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form
          class="login_from"
          :rules="rules"
          :model="loginFrom"
          ref="loginFromRef"
        >
          <h1>Hello</h1>
          <h2>欢迎来到硅谷甄选</h2>
          <el-form-item prop="username">
            <el-input
              :prefix-icon="User"
              v-model="loginFrom.username"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              :prefix-icon="Lock"
              type="password"
              v-model="loginFrom.password"
              show-password
            ></el-input>
          </el-form-item>
          <el-button
            class="login_btn"
            size="default"
            type="primary"
            @click="login"
            :loading="loading"
          >
            登录
          </el-button>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import useUserStore from '@/store/modules/user'
import { ElNotification } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { getTimeStr } from '@/utils/times'

let $route = useRoute()
let $router = useRouter()
let userStore = useUserStore()

let loginFrom = reactive({
  username: '',
  password: '',
})

const loginFromRef = ref()
const rules = {
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 5, max: 12, message: '用户长度应在5到12位之间', trigger: 'change' },
  ],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
}

let loading = ref(false)

const login = async () => {
  await loginFromRef.value.validate()
  loading.value = true
  try {
    await userStore.userLogin(loginFrom)
    loading.value = false
    ElNotification({
      type: 'success',
      message: '欢迎回来',
      title: `HI,${getTimeStr()}！`,
    })
    //编程式导航跳转到首页
    if ($route.query.redirect) {
      $router.push($route.query.redirect + '')
    } else {
      $router.push('/')
    }
  } catch (error) {
    ElNotification({
      type: 'error',
      message: (error as Error).message,
    })
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.login_container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: cover;
}

.login_from {
  width: 70%;
  top: 35vh;
  position: relative;
  background: url('@/assets/images/login_form.png') no-repeat;
  background-size: cover;
  padding: 40px 80px;
  h1 {
    color: white;
    font-size: 40px;
  }
  h2 {
    color: white;
    font-size: 20px;
    margin: 20px 0px;
  }
}

.login_btn {
  width: 100%;
}
</style>
